package es.geodata.gvsig.extLinkedTables;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import javax.swing.JOptionPane;

import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
import com.iver.andami.PluginServices;
import com.iver.andami.plugins.Extension;
import com.iver.andami.ui.mdiManager.IWindow;
import com.iver.cit.gvsig.ProjectExtension;
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
import com.iver.cit.gvsig.fmap.layers.FLayer;
import com.iver.cit.gvsig.fmap.layers.FLayers;
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
import com.iver.cit.gvsig.fmap.layers.VectorialFileAdapter;
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
import com.iver.cit.gvsig.project.ProjectFactory;
import com.iver.cit.gvsig.project.documents.ProjectDocument;
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
import com.iver.cit.gvsig.project.documents.view.gui.View;


public class LinkedTablesExtension extends Extension {

	private static Properties iniProperties = new Properties();	   	
	private FLyrVect layerV;
	
	
	public void execute(String actionCommand) {
	
		IWindow window = PluginServices.getMDIManager().getActiveWindow();		
		View vista = (View) window;
		FLayers layers = vista.getMapControl().getMapContext().getLayers();
		FLayer[] activeLayers;
		if((activeLayers = layers.getActives()).length > 0) {
			for(int i=0; i<activeLayers.length; i++) {
				if(activeLayers[i] instanceof FLyrVect) {
					layerV = (FLyrVect) activeLayers[i];
					ProjectTable ptMain = getProjectTable();		
					ProjectTable ptLinked = getLinkedProjectTable(ptMain);
					if (ptLinked != null){
						LinkedTablesForm dialog = new LinkedTablesForm(layerV, ptMain, ptLinked, iniProperties);
						if (dialog.init()) {
							PluginServices.getMDIManager().addCentredWindow(dialog);
						}
					}
				}
			}
		}		
		
	}
	
	
	private ProjectTable getProjectTable() {
		
		try {
			
			ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
			ProjectTable projectTable = ext.getProject().getTable((AlphanumericData) layerV);
			EditableAdapter ea = null;
			ReadableVectorial rv = layerV.getSource();
			if (rv instanceof VectorialEditableAdapter){
				ea = (EditableAdapter) layerV.getSource();
			}
			else{
				ea = new EditableAdapter();
				SelectableDataSource sds= layerV.getRecordset();
				ea.setOriginalDataSource(sds);
			}
	    	if (projectTable == null) {
				projectTable = ProjectFactory.createTable("taula aux" + ": " + layerV.getName(), ea);
				projectTable.setProjectDocumentFactory(new ProjectTableFactory());
				projectTable.setAssociatedTable((AlphanumericData) layerV);
				ext.getProject().addDocument(projectTable);
				projectTable.setModel(ea);
			}
	    	
			if (rv instanceof VectorialFileAdapter){
				VectorialFileAdapter vfa = (VectorialFileAdapter) rv;
				File file = vfa.getFile();
				System.out.println(file.getAbsolutePath());
				System.out.println(file.getParent());
			}
	    	
			return projectTable;							
		
		} catch (ReadDriverException e) {
			e.printStackTrace();
		}
		
		return null;
				
	}
	
	
	private ProjectTable getLinkedProjectTable(ProjectTable ptMain) {
		
		ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
		ArrayList<ProjectDocument> tables = ext.getProject().getDocumentsByType(ProjectTableFactory.registerName);
		String tableName = ptMain.getLinkTable();
		
		for (int i = 0; i < tables.size(); i++) {					

			ProjectTable ptLinked = (ProjectTable) tables.get(i);
			if (ptLinked.getName().equals(tableName)){
				return ptLinked;	
			}
						
			/*
			AlphanumericData ad = pt.getAssociatedTable();
			try {
				SelectableDataSource sds = ad.getRecordset();
				if (sds.getName().equals(tableName)) {
				//if (((ProjectTable) tables.get(i)).getAssociatedTable().getRecordset().getName().equals(tableName)) {						
					return (ProjectTable) tables.get(i);																				
				}
			} 
			catch (ReadDriverException e) {
				e.printStackTrace();
			}
			*/		
					
		}	
		
		return null;
		 
	}
	
	
	private boolean hasLinkedTable() {
		ProjectTable ptMain = getProjectTable();
		String sTable = null;
		if (ptMain != null){
			sTable = ptMain.getLinkTable();
		}
		return sTable != null;
	}
	
	
	public boolean checkConfigFile(){

		String sFile = PluginServices.getPluginServices(this).getPluginDirectory().getParent() + LinkedTablesPreferences.CONFIG_FILE;		
		File iniFile = new File(sFile);
  		try {
   			iniProperties.load(new FileInputStream(iniFile));
		} catch (FileNotFoundException e) {
			showError("error_notfound", sFile, "app_title");
			return false;			
		} catch (IOException e) {
			showError("error_io", sFile, "app_title");	
			return false;			
		} 		
		return true;
		
	}
	
	
    static void showError(String msg, String param, String title){
    	JOptionPane.showMessageDialog(null, PluginServices.getText(LinkedTablesPreferences.CONFIG_PLUGIN, msg) + param,
    		PluginServices.getText(LinkedTablesPreferences.CONFIG_PLUGIN, title), JOptionPane.WARNING_MESSAGE);
    }		
	
	
	public void initialize() {
		checkConfigFile();		
	}

	
	public boolean isEnabled() {					
		 
		IWindow window = PluginServices.getMDIManager().getActiveWindow();
		if (window instanceof View) {
			View vista = (View) window;
			FLayers layers = vista.getMapControl().getMapContext().getLayers();
			FLayer[] activeLayers;
			if((activeLayers = layers.getActives()).length > 0) {
				for(int i=0; i<activeLayers.length; i++) {
					if(activeLayers[i] instanceof FLyrVect) {
						layerV = (FLyrVect) activeLayers[i];
						if(hasLinkedTable()) return true;
					}
				}
			}
		}						
		 		
		return false;
		
	}
	

	public boolean isVisible() {
		return true;
	}
	
}